using UnityEngine;
using System.Collections;

public class PlayerAttack : MonoBehaviour {
	public float AttackCooldown;
	private float _attackTimer;
	
	private bool _attackStarted;
	private float _attackCharge;
	
	// Use this for initialization
	void Start () {
		AttackCooldown = 1;
		_attackTimer = AttackCooldown;
	}
	
	// Update is called once per frame
	void Update () {
		if (_attackTimer > 0)
		{
			_attackTimer -= Time.deltaTime;
		}
			
		if (_attackTimer < 0)
		{
			_attackTimer = 0;
		}
		
		if (_attackStarted)
		{
			_attackCharge += Time.deltaTime;
		}
		
		if (_attackTimer == 0 &&! _attackStarted && Input.GetMouseButtonDown(0)) {
			StartAttack();
		}
		if (_attackStarted && Input.GetMouseButtonUp(0)) {
			EndAttack();
		}
	}
	
	private void StartAttack() {
		_attackTimer = AttackCooldown;
		_attackStarted = true;
		_attackCharge = 0;
	}
	
	private void EndAttack() {
			var mousePos = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 3));
			var direction = (mousePos - transform.position).normalized;
			
			var projectile = (GameObject) Instantiate((GameObject) Resources.Load("Projectile", typeof(GameObject)), transform.position + (direction * .25f), transform.rotation);
			
			projectile.rigidbody.velocity += (direction) * 20;
			
			_attackStarted = false;
	}
}
